<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\BuilderPlus\components\Button;
use addons\BuilderPlus\components\Column;
use addons\BuilderPlus\components\Edit;
use addons\BuilderPlus\components\Search;
use addons\BuilderPlus\facade\Table;
use app\admin\validate\AdminPassword;
use app\common\tool\Result;
use app\common\model\Role;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\View;
use think\Response;

class Admin extends Base
{
    public function getOptions(): array
    {
        return [
            'pk' => 'id',
            'model' => \app\common\model\Admin::class,
            'validate' => \app\admin\validate\Admin::class,
            'with' => ['role'],
            'fast' => [
                'save' => '_save',
                'reset' => 'reset'
            ]
        ];
    }

    public function index(): string
    {
        return Table::init($this)
            ->addColumns([
                ['id', 'ID', fn(Column $col) => $col->width(80)],
                ['admin_name', '用户名', fn(Column $col) => $col->width(150), fn(Edit $e) => $e->require()],
                ['mobile', '手机号', fn(Column $col) => $col->width(150), fn(Edit $e) => $e->number()->require()],
                ['role_id', '角色', fn(Column $col) => $col->templet('{{d.role?d.role.title:""}}'),
                    fn(Edit $e) => $e->select(Admin::getRole())->require()
                ],
                ['password', '登录密码', fn(Column $col) => $col->hide(), fn(Edit $e) => $e->password()],
                ['comment', '备注', null, fn(Edit $e) => $e->text()],
                ['status', '状态', fn(Column $col) => $col->switch('启用|禁用', '1|0')],
                ['is_lock', '权限', fn(Column $col) => $col->switch('启用|禁用', '1|0')],
                ['last_time', '最后登录时间', fn(Column $col) => $col->width(150)],
                ['create_time', '添加时间', fn(Column $col) => $col->width(150)],
                ['update_time', '更新时间', fn(Column $col) => $col->width(150)]
            ])
            ->addTopButtons([
                'add',
                'password' => fn(Button $btn) => $btn->title('重置登录密码')
                    ->icon('layui-icon-leaf')
                    ->class('danger')
                    ->url(url('reset')->build())
                    ->placeholder('默认密码123456')
                    ->event('prompt')
            ])
            ->addRightButtons(['edit', 'delete'])
            ->addSearch([
                ['admin_name__mobile__comment', '用户名/手机号/备注', fn(Search $search) => $search->condition('Like')],
                ['role_id', '角色类型', fn(Search $search) => $search->type('select')->optionValue(Admin::getRole())]
            ])
            ->specifyQuery([['id', '>', 1]])
            ->fetch();
    }

    public static function getRole(): array
    {
        return Role::where('id', '>', 1)->column('title', 'id');
    }

    public function delete(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn($this->model::_delete($param, $this->admin));
    }

    public function password(): Response|string
    {
        if ($this->request->isPost()) {
            try {
                $param = $this->request->post();
                validate(AdminPassword::class)->check($param);
                if (md5($param['old']) != $this->admin->password) return Result::fail('原密码错误');
                $this->model::update(['password' => md5($param['password'])], ['id' => $this->admin->id]);
                \app\common\model\Logs::adds('管理员【' . $this->admin->admin_name . '】修改了密码');
                Session::delete('admin_id');
                Session::delete('password_token');
                Cookie::delete('local_admin_token');

                return Result::success('修改成功');
            } catch (\Exception $e) {

                return Result::fail($e->getError());
            }
        }

        return View::fetch();
    }
}